package users;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import app.Usr;

public class SecurityOfficer {
    private static final String UNIT_NAME = "Erestraunt";
    private static EntityManagerFactory factory;

    
    public void deleteUser(int id) {
	factory = Persistence.createEntityManagerFactory(UNIT_NAME);
	EntityManager em = factory.createEntityManager();
	Usr user = null;

	try {
	    user = em.find(Usr.class, id);

	    if (user != null) {
		em.getTransaction().begin();
		em.remove(user);
		em.getTransaction().commit();
	    }

	} finally {
	    em.close();
	}
    }

    
    
    public void addUser(String name, int userType, String login, String password) {
	factory = Persistence.createEntityManagerFactory(UNIT_NAME);
	EntityManager em = factory.createEntityManager();

	try {
	    Usr newUser = new Usr();
	    newUser.setName(name);
	    newUser.setUsrType(userType);
	    newUser.setLogin(login);
	    newUser.setPassword(password);

	    em.getTransaction().begin();
	    em.persist(newUser);
	    em.getTransaction().commit();

	} finally {
	    em.close();
	}
    }

    
    
    public void updateUser(int id, int userType) {
	factory = Persistence.createEntityManagerFactory(UNIT_NAME);
	EntityManager em = factory.createEntityManager();

	Usr user = null;
	try{
	user = em.find(Usr.class, id);
	if (user != null) {
	    em.getTransaction().begin();
	    user.setUsrType(userType);
	    em.getTransaction().commit();
	}
	} finally {
	    em.close();
	}
    }
}
